package lipengfei.botaiframework.mybatisplus.extend.core;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lipengfei.botaiframework.utils.SnowFlakeUtil;
import lipengfei.botaiframework.utils.cache.ThreadLocalCache;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @description: 填充创建时间，创建人，更新时间，更新人
 * @author: lipf
 */
@Component
public class BaseMetaObjectHandler implements MetaObjectHandler {
   
	/*** 唯一标识 */
    public static final String ID = "id";
	/*** 删除标记 */
    public static final String DEL_FLAG = "delFlag";
    /*** 创建时间*/
    public static final String CREATED_BY = "createdBy";
    /*** 创建时间*/
    public static final String CREATED_TIME = "createdTime";
    /*** 创建时间*/
    public static final String UPDATED_BY = "updatedBy";
    /*** 更新时间*/
    public static final String UPDATED_TIME = "updatedTime";
    /*** 版本信息乐观锁*/
    public static final String VERSION = "version";


    public void insertFill(MetaObject metaObject) {

        Object ID_VALUE=getFieldValByName(ID,metaObject);
        if (ID_VALUE == null ) {
            setFieldValByName(ID, SnowFlakeUtil.nextId(), metaObject);
        }
        // 创建用户
    	String CREATE_BY_VALUE=(String) getFieldValByName(CREATED_BY,metaObject);
        String onlineUserId = (String) ThreadLocalCache.getCache("onlineUserId");
        if (CREATE_BY_VALUE == null && onlineUserId!=null ) {

            setFieldValByName(CREATED_BY, onlineUserId, metaObject);
        }
        String UPDATE_BY_VALUE=(String) getFieldValByName(UPDATED_BY,metaObject);
        if (UPDATE_BY_VALUE == null && onlineUserId!=null  ) {
            setFieldValByName(UPDATED_BY, onlineUserId, metaObject);
        }
        // 创建时间
        setFieldValByName(CREATED_TIME, new Date(), metaObject);
        setFieldValByName(UPDATED_TIME, new Date(), metaObject);
        setFieldValByName(VERSION, Integer.parseInt("1"), metaObject);
        //System.out.println(Integer.parseInt("1"));

        setFieldValByName(DEL_FLAG, "0", metaObject);
    }



    public void updateFill(MetaObject metaObject) {
        String UPDATE_BY_VALUE=(String) getFieldValByName(UPDATED_BY,metaObject);
        String onlineUserId = (String) ThreadLocalCache.getCache("onlineUserId");
        if (UPDATE_BY_VALUE == null  && onlineUserId!=null  ) {
            setFieldValByName(UPDATED_BY, onlineUserId, metaObject);
        }
        // 更新用户
        setFieldValByName(UPDATED_TIME, new Date(), metaObject);
    }



}